package dao;

import entity.BookManage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookManageDao extends BaseDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    public List<BookManage> bookList(){
        conn = super.getConnection();
        List<BookManage> list = new ArrayList<>();
        BookManage bookManage = null;
        try{
            String sql = "select * from bookmanage order by time desc";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                bookManage = new BookManage();
                bookManage.setId(rs.getInt("id"));
                bookManage.setName(rs.getString("name"));
                bookManage.setAuthor(rs.getString("author"));
                bookManage.setTime(rs.getString("time"));
                bookManage.setType(rs.getInt("type"));
                list.add(bookManage);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return list;
    }

    public int bookAdd(BookManage bookManage){
        conn = super.getConnection();
        int i = 0;
        try{
            String sql = "insert into bookmanage(name,author,time,type)values(?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,bookManage.getName());
            ps.setString(2,bookManage.getAuthor());
            ps.setString(3,bookManage.getTime());
            ps.setInt(4,bookManage.getType());
            i = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return i;
    }

    public int bookDelete(int id){
        conn = super.getConnection();
        int i = 0;
        try{
            String sql = "delete from bookmanage where id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            i = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return i;
    }
}
